package dtd.PHS.VND_ExchangeRate;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.DisplayMetrics;
import dtd.PHS.VND_ExchangeRate.VCB_ERate.MyCurrency;
import dtd.PHS.VND_ExchangeRate.VCB_ERate.VND_ExchangeRate;

public class MyUtility {
	public static String[] passData_Calculate2PreviewSMS_currencies;
	public static String[] passData_Calculate2PreviewSMS_amount;
	public static String passData_Calculate2PreviewSMS_inputDate;
	public static HashMap<MyCurrency, Integer> mapCurrency2ResourceID;
	static {
		mapCurrency2ResourceID = new HashMap<MyCurrency, Integer>();
		mapCurrency2ResourceID.put(MyCurrency.AUD, new Integer(R.drawable.aud_flag));
		mapCurrency2ResourceID.put(MyCurrency.CAD, new Integer(R.drawable.cad_flag));
		mapCurrency2ResourceID.put(MyCurrency.CHF, new Integer(R.drawable.chf_flag));
		mapCurrency2ResourceID.put(MyCurrency.EUR, new Integer(R.drawable.eur_flag));
		mapCurrency2ResourceID.put(MyCurrency.GBP, new Integer(R.drawable.gbp_flag));
		mapCurrency2ResourceID.put(MyCurrency.HKD, new Integer(R.drawable.hkd_flag));
		mapCurrency2ResourceID.put(MyCurrency.JPY, new Integer(R.drawable.jpy_flag));
		mapCurrency2ResourceID.put(MyCurrency.SGD, new Integer(R.drawable.sgd_flag));
		mapCurrency2ResourceID.put(MyCurrency.THB, new Integer(R.drawable.thb_flag));
		mapCurrency2ResourceID.put(MyCurrency.USD, new Integer(R.drawable.usd_flag));

	}
	static public boolean isValidLong(String numberStr) {
		try {
			double d = Long.parseLong(numberStr);
			if ( d >= 0 ) return true;
			return false;
		} catch (NumberFormatException ne) {
			return false;
		}	
	}
	
	static public int newCursorPosition(int prePos,String preS,String aftS) {			
		int aftPos = prePos;			
		if (preS.length() < aftS.length()) {
			//Insert a char	
			aftPos = prePos + 1 + ((preS.length() + 1) % 4 == 0 ? 1:0);				
		} else if (preS.length() > aftS.length()){
			//Delete a char by Backspace			
			aftPos = prePos - 1;
			if ( prePos == 1) return 0;
			aftPos = aftPos - ((preS.length() - 1) % 4 == 0 ? 1:0);				
		}				
		//Only the case insert/delete at the end
		//	prove why is this case enough
		return aftPos;
	}
	static public String getRidOfComma(String numberStr) {	
		return numberStr.replaceAll(",", "");
	}

	static public String formatCurrency(String amount) {
		amount = getRidOfComma(amount);
		int cnt = 0;
		String x = new String("");
		for(int i = amount.length()-1; i>=0 ; i--) {
			cnt++;
			x = amount.charAt(i)+x;
			if ( cnt == 3 && i != 0) {
				cnt = 0;			
				x = ','+x ;
			}
		}
		return x;
	}

	static public String formatRate(double rate) {
		int intPart = (int) rate;
		int fraPart = (int)((rate - intPart)*100);
		String strFrag = Integer.toString(fraPart);
		if (fraPart < 10) strFrag = "0"+ strFrag;
		String numStr = 
			formatCurrency(Integer.toString(intPart)) +
			"."+
			strFrag;

		return numStr;
	}
	public static boolean connectedToInternet(Context context) {		
		ConnectivityManager conMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);  
		NetworkInfo info = conMgr.getActiveNetworkInfo();  
		if ( info != null && info.isConnected() ) {
			return true;
		} else	return false;
	}
	public static boolean inThePast(String lastOnlineDate) {
		MyDate lastDate = extractDate(lastOnlineDate,"/");		
		MyDate today =  extractDate(getCurrentDate(),"/");
		
		if ( lastDate.year < today.year ) return true;
		if ( lastDate.year > today.year ) return false;

		//Same year, so compare Month
		if ( lastDate.month < today.month ) return true;
		if ( lastDate.month > today.month) return false;

		//Same month, so compare Day
		if ( lastDate.day < today.day ) return true;
		if ( lastDate.day > today.day ) return false;

		//All the same
		return false;
	}
	static private MyDate extractDate(String lastOnlineDate, String sep) {		
		String[] words = lastOnlineDate.replaceAll(" ","").split(sep);
		return new MyDate(
				Integer.parseInt(words[2]),
				Integer.parseInt(words[1]),
				Integer.parseInt(words[0]));		
	}
	
    public static String getCurrentDate() {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Date date = new Date();
        return dateFormat.format(date);
    }
	public static String createSMSContent(
			Context context,
			String currency,
			VND_ExchangeRate rate,
			String date) {		
		String content = context.getString(R.string.SMS_Title) + " " + date + "\n";
		content += createSMSBodyForRate(rate, context);
		content += "\n"+ context.getString(R.string.SMSBottomLine);
		return content;
	}
	public static void broadcastSMSIntent(Context context,String content) {
		Intent sendIntent = new Intent(Intent.ACTION_VIEW);
		sendIntent.putExtra("sms_body", content); 
		sendIntent.setType("vnd.android-dir/mms-sms");
		context.startActivity(sendIntent);
	}
	public static String createSMSContent(
			Context context,
			ArrayList<VND_ExchangeRate> rates, 
			String date) {
		
		String content = context.getString(R.string.SMS_Title) + " " + date + "\n";
		for(VND_ExchangeRate rate : rates) {
			content += createSMSBodyForRate(rate, context);
			content += "----------\n";
		}
		content += "\n"+ context.getString(R.string.SMSBottomLine);
		return content;
	}
	
	public static String createSMSBodyForRate(VND_ExchangeRate rate,Context context) {
		String content = "";
		content += context.getString(R.string.BuyingSMS)+"("+rate.currency.toString()+")"+ ": " + formatRate(rate.buying) + "\n";
		content += context.getString(R.string.TransferSMS)+"("+rate.currency.toString()+")"+": " + formatRate(rate.transfer)+ "\n";
		content += context.getString(R.string.SellingSMS)+"("+rate.currency.toString()+")"+": " + formatRate(rate.selling) + "\n";
		return content;
	}
	
	public static MyCurrency[] getCurrenciesExceptVND() {
		int nCurrency = MyCurrency.values().length-1;
		MyCurrency[] currList = new MyCurrency[nCurrency];
		int i = 0;
		for(MyCurrency c:MyCurrency.values()) {
			if ( c != MyCurrency.VND) currList[i++] = c;
		}
		return currList;
	}

	public static void saveLanguageOption(Context context, String languageToLoad) {
		SharedPreferences settings = context.getSharedPreferences(context.getString(R.string.PreferenceName), Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(context.getString(R.string.LanguageToLoadSetting), languageToLoad);
		editor.commit();
	}

	public static void changeLanguage(Context context, String languageToLoad) {
		if (languageToLoad == null ) languageToLoad = context.getString(R.string.DefaultLanguage);
		Resources res = context.getResources();
		// Change locale settings in the app.
		DisplayMetrics dm = res.getDisplayMetrics();
		android.content.res.Configuration conf = res.getConfiguration();
		conf.locale = new Locale(languageToLoad);
		res.updateConfiguration(conf, dm);
	}

	public static String getSetting(Context context,String string) {
		SharedPreferences settings = context.getSharedPreferences(context.getString(R.string.PreferenceName), Context.MODE_PRIVATE);
		String language = settings.getString(context.getString(R.string.LanguageToLoadSetting), null);
		return language;
	}

	public static void callOnEveryActivity(Context context) {
		((Activity)context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		MyUtility.changeLanguage(context,MyUtility.getSetting(context,context.getString(R.string.LanguageToLoadSetting)));

		
	}

	public static void forceActivityRestart(Activity act) {
		act.startActivity(act.getIntent()); 
		act.finish();	
	}

	public static void switchToHomeScreen(Activity act) {

		Intent setIntent = new Intent(Intent.ACTION_MAIN);
		setIntent.addCategory(Intent.CATEGORY_HOME);
		setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		act.startActivity(setIntent); 
		
	}


}
